import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, message as msg, Modal} from 'antd';
import {PAGE, TABLE, PAGINATION_OPTIONS, FORM_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, DATE_FORMAT} from '../constants';
import TextInput from 'Shared/components/TextInput';
import DateRangePicker from 'Shared/components/DateRangePicker';
import {formatDateTime} from '../utils';
import SelectAlert from '../common/SelectAlert';
import {conventSorter, computeSelectedRows} from './utils';
import styles from './style.css';
import moment from 'moment';
import {getTechnologyActivityDetail} from './api';
import {injectIntl, formatMessage} from './intl';
import WrappedInputVIN from './WrappedInputVIN';
const FormItem = Form.Item;
const MultiSelectAlert = SelectAlert.Multi;
const widths = {
    width: '40%',
    textAlign: 'center'
};
class TechnologyActivityVehicleSelectPanel extends PureComponent {
    state = {
        beginVin: '',
        endVin: '',
        saleDate: [],
        engineCode: '',
        isFetching: false,
        data: {},
        message: '',
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        currentCondition: {},
        selectedRowKeys: [],
        selectedRows: []
    }
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = this.state.currentCondition;
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }

    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }

    onQuery = condition => {
        this.setState({isFetching: true});
        getTechnologyActivityDetail(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }
    onClickSearchBtn = () => {
        const condition = {
            beginVin: this.state.beginVin,
            endVin: this.state.endVin,
            saleDate: this.state.saleDate,
            engineCode: this.state.engineCode,
            technologyActivityId: this.props.technologyActivityId,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        const saleDateDate = (condition = {}) => {
            const {saleDate, ...others} = condition;
            if(!saleDate || saleDate.length === 0) return condition;
            return {
                ...others,
                beginSaleDateDate: moment(saleDate[0]).toISOString(),
                endSaleDateDate: moment(saleDate[1]).toISOString(),
            };
        };
        this.onQuery(saleDateDate(condition));
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChange = (value, name) => {
        this.setState({[name]: value});
    }

    onClickReset = () => {
        this.setState({
            beginVin: '',
            endVin: '',
            saleDate: [],
            engineCode: '',
        });
    }

    onChangeRadio = (selectedRowKeys, selectedRows) => {
        this.setState({
            selectedRowKeys,
            selectedRows
        });
    }

    onCloseTag = () => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: []
        });
    }

    onSubmit = () => {
        if(!this.state.selectedRows.length)
            return msg.warn(formatMessage({
                id: 'technologyActivityVehicleSelectPanel.validate.title',
                defaultMessage: '请选择技术升级车辆清单信息'
            }));
        this.props.onSelect(this.state.selectedRows);
    }
    
    render() {
        const {isFetching, data, message} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: formatMessage({
                    id: 'technologyActivityVehicleSelectPanel.column.vin',
                    defaultMessage: 'VIN'
                }),
                dataIndex: 'vin',
            },
            {
                title: formatMessage({
                    id: 'technologyActivityVehicleSelectPanel.column.engineCode',
                    defaultMessage: '发动机号'
                }),
                dataIndex: 'engineCode',
            },
            {
                title: formatMessage({
                    id: 'technologyActivityVehicleSelectPanel.column.saleDate',
                    defaultMessage: '实销日期'
                }),
                dataIndex: 'saleDate',
                render: text => formatDateTime(text, DATE_FORMAT),
            },
            {
                title: formatMessage({
                    id: 'technologyActivityVehicleSelectPanel.column.mileage',
                    defaultMessage: '行驶里程(KM)'
                }),
                dataIndex: 'mileage',
            },
            {
                title: formatMessage({
                    id: 'technologyActivityVehicleSelectPanel.column.isUsed',
                    defaultMessage: '是否参加'
                }),
                dataIndex: 'isUsed',
                render: text => text ? formatMessage({
                    id: 'technologyActivityVehicleSelectPanel.column.y',
                    defaultMessage: '是'
                }) : formatMessage({
                    id: 'technologyActivityVehicleSelectPanel.column.n',
                    defaultMessage: '否'
                }),
            }
        ];
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                const rows = computeSelectedRows(this.state.selectedRowKeys, this.state.selectedRows, selectedRowKeys, selectedRows);
                this.setState({
                    selectedRowKeys,
                    selectedRows: rows
                });
            }
        };
        return (
            <Modal
                title={formatMessage({
                    id: 'technologyActivityVehicleSelectPanel.show.Query',
                    defaultMessage: '技术升级车辆清单查询'
                })}
                width="60%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Row className="form-standard">
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'technologyActivityVehicleSelectPanel.show.beginVin',
                            defaultMessage: 'VIN'
                        })}
                        {...FORM_OPTIONS.item}>
                            <WrappedInputVIN
                                style={widths}
                                name={['beginVin', 'endVin']}
                                onBlur={this.onChange}
                                value={[this.state.beginVin, this.state.endVin]}/>
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'technologyActivityVehicleSelectPanel.show.engineCode',
                            defaultMessage: '发动机号'
                        })}
                        {...FORM_OPTIONS.item}>
                            <TextInput
                                name="engineCode"
                                value={this.state.engineCode}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={formatMessage({
                                id: 'technologyActivityVehicleSelectPanel.form.saleDate',
                                defaultMessage: '实销日期'
                            })}{...FORM_OPTIONS.item}>
                            <DateRangePicker
                                name="saleDate"
                                value={this.state.saleDate}
                                onChange={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                        <Button
                            type="primary"
                            loading={isFetching}
                            onClick={this.onClickSearchBtn}>
                            {formatMessage({
                                id: 'technologyActivityVehicleSelectPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.onClickReset}>{formatMessage({
                            id: 'technologyActivityVehicleSelectPanel.btn.reset',
                            defaultMessage: '重置'
                        })}</Button>
                    </Col>
                </Row>
                <Divider className={styles.divider}/>
                <MultiSelectAlert data={this.state.selectedRows}
                    onConfirm={this.onSubmit}
                    onDelete={this.onCloseTag}
                    onDeleteAll={this.onCloseTag}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={data.content}
                    rowClassName={styles.tableCursor}
                    columns={columns}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={rowSelection}
                    locale={{
                        emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                    }}
                    {...TABLE}/>
            </Modal >
        );
    }
}

TechnologyActivityVehicleSelectPanel.propTypes = {
    onSelect: PropTypes.func.isRequired,
    technologyActivityId: PropTypes.string,
    onCancel: PropTypes.func,
};

export default injectIntl(TechnologyActivityVehicleSelectPanel);
